<template>
  <div class="employee_manage">
    <el-form :inline="true" size="mini">
      <el-form-item label="服务区域">
        <el-cascader
          :options="locations"
          v-model="location"
          change-on-select
          style="min-width:250px"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="服务类型">
        <el-select v-model="prodIds" placeholder="请选择">
          <el-option
            v-for="item in products"
            :key="item.templateId"
            :label="item.name"
            :value="item.templateId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-button type="primary" size="mini" @click="clearSearch()">清空条件</el-button>
      <el-button type="primary" size="mini" @click="searchData()">搜索</el-button>
      <el-button type="primary" size="mini" @click="exportExcel()">积分导出</el-button>
    </el-form>
    <el-table size="mini" :data="employeeList" height="500">
      <el-table-column label="姓名">
        <template slot-scope="scope">
          <span class="fa fa-star" v-if="scope.row.offerType==='STAR'"></span>
          {{scope.row.name}}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="联系方式"></el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">{{scope.row.status==="ENABLE"?"已启用":"已禁用"}}</template>
      </el-table-column>
      <el-table-column label="积分总额">
        <template slot-scope="scope">{{scope.row.summary.creditTotal}}</template>
      </el-table-column>
      <el-table-column label="积分余额">
        <template slot-scope="scope">{{scope.row.summary.creditRemain}}</template>
      </el-table-column>
      <el-table-column label="已完成订单数">
        <template slot-scope="scope">{{scope.row.summary.orderQuantityDone}}</template>
      </el-table-column>
      <el-table-column label="服务中订单数">
        <template slot-scope="scope">{{scope.row.summary.orderQuantityServing}}</template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <a class="t-link" v-if="scope.row.offerType!=='STAR'" @click="addStar(scope.row)">添加星标</a>
          <a class="t-link" v-if="scope.row.offerType==='STAR'" @click="removeStar(scope.row)">移除星标</a>
          <a class="t-link" v-if="scope.row.status==='DISABLE'" @click="changeStatus(scope.row)">启用</a>
          <a class="t-link" v-if="scope.row.status==='ENABLE'" @click="changeStatus(scope.row)">禁用</a>
        </template>
      </el-table-column>
    </el-table>
    <div class="paging-block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.pageNum"
        :page-sizes="[15, 20, 30, 40]"
        :page-size="pagination.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      ></el-pagination>
    </div>
    <el-dialog :visible.sync="auditDialogVisible" width="70%" top="5vh">
      <employ-audit></employ-audit>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rejectAudit()">拒绝申请</el-button>
        <el-button type="primary" @click="passAudit()">通过申请</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import employAudit from "./employ_audit";
import { BACKEND_URL } from "@/config/config";
import ajax from "@/api/ajax";
import {
  getEmployeeListV2,
  getArea,
  starEmployee,
  removeStarEmployee
} from "@/api/employee_manage";
import { fetchProductList } from "@/api/product_manage";
import {
  EMPLOYEE_STATUS,
  DEFAULT_AUDIT_PASS_REMARK,
  DEFAULT_AUDIT_REFUSE_REMARK,
  SUCCESS_CODE
} from "@/config/config";

export default {
  name: "employee_manage",
  components: { employAudit },
  data() {
    let employeeStatus = Object.assign({}, EMPLOYEE_STATUS);
    delete employeeStatus.APPLYING;
    return {
      EMPLOYEE_STATUS: employeeStatus,
      auditDialogVisible: false,
      employeeStatus: employeeStatus,
      employeeList: [], // 业务员列表
      locations: [], // 所有的服务区域
      products: [], // 产品列表
      location: [], // 选中的服务区域
      prodIds: [], // 选中的服务
      pagination: {
        limit: 15, // 每页显示数据条数
        pageNum: 1, // 当前页
        total: 0 // 数据总条数
      }
    };
  },
  computed: {
    ...mapState("employeeManage", {
      productCatalogue: state => state.productCatalogue,
      // employeeList: state => state.employeeList,
      selectedEmployee: state => state.selected
    })
  },
  methods: {
    ...mapActions("employeeManage", [
      "searchEmployee",
      "selectEmployee",
      "auditEmployee"
    ]),
    toAudit(scope) {
      console.log(scope);
      console.log(this);
      this.auditDialogVisible = true;
      this.selectEmployee(scope.row);
    },
    toCreditOP(scope) {},
    toCreditDetail(scope) {},
    getSearchParam() {
      let searchParams = Object.assign(
        {},
        { ...this.pagination },
        { location: this.location.join("-") }
      );
      if (this.prodIds) {
        searchParams = Object.assign({}, searchParams, {
          prodId: this.prodIds
        });
      }
      this.clearEmptyParams(searchParams);
      return searchParams;
    },
    searchData() {
      getEmployeeListV2(this.getSearchParam()).then(resp => {
        let data = resp.data;
        if (data.status === SUCCESS_CODE) {
          this.employeeList = data.data.results;
          this.pagination.total = data.total;
        }
      });
    },
    getLocations() {
      getArea().then(resp => {
        let data = resp.data;
        if (data.status === SUCCESS_CODE) {
          console.log(data);
          let locations = JSON.parse(data.data);
          locations = locations.map(location => {
            return {
              label: location.name,
              value: location.name,
              children: location.city.map(city => {
                return {
                  label: city.name,
                  value: city.name,
                  children: city.area.map(area => {
                    return {
                      label: area.name,
                      value: area.name
                    };
                  })
                };
              })
            };
          });
          this.locations = locations;
        }
      });
    },
    getProducts() {
      fetchProductList().then(resp => {
        let data = resp.data;
        if (data.status === SUCCESS_CODE) {
          this.products = data.data;
        }
      });
    },
    clearSearch() {
      this.prodIds = "";
      this.location = [];
      this.searchData();
    },
    addStar(employee) {
      this.$swal({
        title: `确定要将"${employee.name}"添加为星标业务员吗？`,
        type: "question",
        showCloseButton: true,
        allowOutsideClick: false
      }).then(result => {
        if (result) {
          if (result.dismiss) return;
          starEmployee(employee.userId).then(resp => {
            let result = resp.data;
            this.handleOpSuccess(result);
            this.searchData();
          });
        }
      });
    },
    removeStar(employee) {
      this.$swal({
        title: `确定要撤销"${employee.name}"的星标业务员吗？`,
        type: "question",
        showCloseButton: true,
        allowOutsideClick: false
      }).then(result => {
        if (result) {
          if (result.dismiss) return;
          removeStarEmployee(employee.userId).then(resp => {
            let result = resp.data;
            this.handleOpSuccess(result);
            this.searchData();
          });
        }
      });
    },
    handleCurrentChange(currentPage) {
      console.log(this.pagination);
      this.pagination.pageNum = currentPage;
      this.searchData();
    },
    handleSizeChange(size) {
      this.pagination.limit = size;
      this.searchData();
    },
    passAudit() {
      this.auditEmployee({
        applyId: this.selectedEmployee.applyId,
        remark: this.tip || DEFAULT_AUDIT_PASS_REMARK,
        status: EMPLOYEE_STATUS.DONE
      });
      this.auditDialogVisible = false;
    },
    rejectAudit() {
      this.auditEmployee({
        applyId: this.selectedEmployee.applyId,
        remark: this.tip || DEFAULT_AUDIT_REFUSE_REMARK,
        status: EMPLOYEE_STATUS.REJECT
      });
      this.auditDialogVisible = false;
    },
    /**
     * 改变禁用状态
     */
    changeStatus(employee) {
      let originalStatus = employee.status;
      let newStatus = originalStatus === "ENABLE" ? "DISABLE" : "ENABLE";
      let tip = originalStatus === "ENABLE"  ? "禁用" : "启用";
      tip = `你确定要${tip}该业务员吗？`;
      this.$swal({
        type: "question",
        title: tip,
        allowOutsideClick: false,
        showCloseButton: true,
        showCancelButton: true,
        cancelButtonText: "取消",
        confirmButtonText: "确定"
      }).then(result => {
        if (!result) return;
        if (result.dismiss) return;
        let url = `/api/sys/user/${employee.userId}/status?status=${newStatus}`;
        ajax.put(url).then(resp => {
          let data = resp.data;
          this.handleOpSuccess(data);
          this.searchData();
        });
      });
    },
    /**
     * 到处积分到excel
     */
    exportExcel() {
      let url = `${BACKEND_URL}/api/export/excel/employee/summary?`;
      let searchParams = this.getSearchParam();
      delete searchParams.limit;
      delete searchParams.pageNum;
      Object.keys(searchParams).forEach(key => {
        url += `${key}=${searchParams[key]}&`;
      });
      window.open(url);
    }
  },
  filters: {
    getServicesStr(services) {
      return services.map(v => v.name).join(",");
    }
  },
  created() {
    this.searchData();
    this.getLocations();
    this.getProducts();
  }
};
</script>

<style>
.paging-block {
  width: 100%;
  text-align: center;
}
</style>
